// dao/UserDAO.java
package main.java.com.cinema.dao;

import main.java.com.cinema.model.User;
import main.java.com.cinema.util.MD5Util;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {
    private static final String USER_FILE = "users.txt";

    public UserDAO() {
        initializeDefaultAdmin();
    }

    private void initializeDefaultAdmin() {
        User admin = findByUsername("admin");
        if (admin == null) {
            // 创建默认管理员账户，密码使用MD5加密
            User adminUser = new User("U001", "admin", "ynuinfo#777", User.Role.ADMIN, "");
            adminUser.setPasswordChanged(true);
            save(adminUser);
        }
    }

    public List<User> findAll() {
        List<User> users = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(USER_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                User user = parseUserFromLine(line);
                if (user != null) {
                    users.add(user);
                }
            }
        } catch (FileNotFoundException e) {
            // 文件不存在，返回空列表
        } catch (IOException e) {
            e.printStackTrace();
        }
        return users;
    }

    public User findById(String userId) {
        List<User> users = findAll();
        for (User user : users) {
            if (user.getUserId().equals(userId)) {
                return user;
            }
        }
        return null;
    }

    public User findByUsername(String username) {
        List<User> users = findAll();
        for (User user : users) {
            if (user.getUsername().equals(username)) {
                return user;
            }
        }
        return null;
    }

    public boolean save(User user) {
        List<User> users = findAll();
        users.add(user);
        return saveAll(users);
    }

    public boolean update(User user) {
        List<User> users = findAll();
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getUserId().equals(user.getUserId())) {
                users.set(i, user);
                return saveAll(users);
            }
        }
        return false;
    }

    public boolean delete(String userId) {
        List<User> users = findAll();
        users.removeIf(user -> user.getUserId().equals(userId));
        return saveAll(users);
    }

    private boolean saveAll(List<User> users) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(USER_FILE))) {
            for (User user : users) {
                writer.write(userToLine(user));
                writer.newLine();
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private String userToLine(User user) {
        return String.join("|",
                user.getUserId(),
                user.getUsername(),
                user.getPassword(),
                user.getRole().name(),
                user.getPhoneNumber() != null ? user.getPhoneNumber() : "",
                user.getRegistrationTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                String.valueOf(user.isPasswordChanged()));
    }

    private User parseUserFromLine(String line) {
        try {
            String[] parts = line.split("\\|");
            if (parts.length >= 7) {
                User user = new User();
                user.setUserId(parts[0]);
                user.setUsername(parts[1]);
                user.setEncryptedPassword(parts[2]); // 使用新方法设置已加密的密码
                user.setRole(User.Role.valueOf(parts[3]));
                user.setPhoneNumber(parts[4].isEmpty() ? null : parts[4]);
                user.setRegistrationTime(LocalDateTime.parse(parts[5], DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                user.setPasswordChanged(Boolean.parseBoolean(parts[6]));
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
